<template>
  <el-row>
    <el-form ref="carouselInfo" :model="carouselInfo" :rules="rules" label-width="100px">
      <el-form-item label="跳转链接" prop="link">
        <el-input v-model="carouselInfo.link" />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否屏蔽" prop="status">
            <el-switch v-model="carouselInfo.status" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否外链" prop="target">
            <el-switch v-model="carouselInfo.target" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="图片" prop="image">
        <el-row>
          <el-col :span="12">
            <el-upload
              ref="upload"
              accept=".jpg,.jpeg,.png,.gif"
              :headers="headers"
              name="src"
              :data="carouselInfo"
              :action="`${host}/user/topic/insertTopic`"
              :limit="limitCount"
              :on-success="successImg"
              :on-error="errorImg"
              list-type="picture-card"
              :on-change="uploadChange"
              :before-upload="uploadBefore"
              :class="{hide:hideUpload}"
              :auto-upload="false"
            >
              <i slot="default" class="el-icon-plus" />
              <div slot="file" slot-scope="{file}">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)"><i class="el-icon-zoom-in" /></span>
                  <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)"><i class="el-icon-delete" /></span>
                </span>
              </div>
            </el-upload>
          </el-col>
          <el-col :span="12">
            <div class="block">
              <el-image style="width: 288px; height: 162px" :src="haveUrl">
                <div slot="error" class="image-slot" />
              </el-image>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-dialog :visible.sync="dialogVisibleImg" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
          <p style="margin: 0">请选择图片上传：支持JPG、PNG、GIF等格式，图片需不大于5M</p>
        </el-row>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="carouselInfo.description" placeholder="简要描述活动信息" maxlength="30" show-word-limit />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('carouselInfo')">保存</el-button>
      </el-form-item>
    </el-form>
  </el-row>
</template>

<script>
import { getToken, getUserId } from '@/utils/auth'
import { adminListTopic } from '@/api/topic'

export default {
  name: 'AddOrUpdateCarousel',
  props: {
    topicId: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      headers: {
        Authorization: getToken(),
        user_id: getUserId()
      },
      hideUpload: false,
      carouselInfo: {
        topicId: this.topicId,
        link: '',
        status: false,
        target: false,
        description: ''
      },
      haveUrl: '',
      dialogImageUrl: '',
      dialogVisibleImg: false,
      disabled: false,
      limitCount: 1,
      rules: {
        link: [{ required: true, message: '请输入完整的链接', trigger: 'blur' }],
        description: [{ required: true, message: '请输入活动描述', trigger: 'blur' }]
      },
      host: process.env.VUE_APP_BASE_API
    }
  },
  created() {
    if (this.topicId !== -1) {
      adminListTopic({ topicId: this.topicId }).then(res => {
        this.carouselInfo.link = res.data[0].link
        this.carouselInfo.description = res.data[0].description
        this.carouselInfo.status = res.data[0].status === 1
        this.carouselInfo.target = res.data[0].target === 1
        this.haveUrl = res.data[0].src
      })
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.$refs.upload.uploadFiles.length !== 1) {
            this.$message.warning('请选择图片')
            return
          }
          this.$refs.upload.submit()
        }
      })
    },
    successImg(response, file, fileList) {
      this.infoLoad = false
      if (response.code === '00000') {
        this.$message({ message: response.message, type: 'success' })
        this.$emit('updateDialog', false)
      } else {
        this.$message({ message: response.message, type: 'error' })
      }
      this.$refs.upload.uploadFiles = []
      this.imageChange()
    },
    errorImg(response, file, fileList) {
      this.hideUpload = false
      this.imageBtn = true
      this.$message({ message: response.message, type: 'error' })
      this.$refs.upload.uploadFiles = []
      this.imageChange()
    },
    uploadChange(file, fileList) {
      this.imageChange()
    },
    uploadBefore(file) {
      if (file.size > 5242880) {
        this.$message.warning('图片上限为5M')
        this.$refs.upload.uploadFiles = []
        this.imageChange()
        return false
      } else if (file.type !== 'image/jpeg' && file.type !== 'image/gif' && file.type !== 'image/jpg' && file.type !== 'image/png') {
        this.$refs.upload.uploadFiles = []
        this.$message.warning('文件类型限制为jpg,jpeg,gif,png')
        this.imageChange()
        return false
      } else {
        this.infoLoad = true
        return true
      }
    },
    imageChange() {
      this.hideUpload = this.$refs.upload.uploadFiles.length >= this.limitCount
      this.imageBtn = this.$refs.upload.uploadFiles.length < this.limitCount
    },
    handleRemove(file) {
      this.$refs.upload.uploadFiles = []
      this.imageChange()
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisibleImg = true
    }
  }
}
</script>

<style scoped>
::v-deep .hide .el-upload--picture-card {
  display: none;
}
</style>
